<template>
	<view class="content">
    <!-- 文章标题 -->
    <view class="title">{{info.title}}</view>
    <!-- 作者信息 -->
    <view class="author">
      <image class="author-avatar" :src="info.avatar"></image>
      <view class="author-info">
        <view class="author-name">{{info.author}}</view>
        <view class="author-time">
          <text class="month">{{info.date}}</text>
          <text class="second">{{info.time}}</text>
        </view>
      </view>
    </view>
    <!-- 文章内容 -->
    <view class="article">
    	<view v-html="info.content"></view>
    </view>
   <!-- THE END --> 
    <view class="end">
      <view class="line"></view>
      THE END
      <view class="line"></view>
    </view>
    
    <!-- share -->
    <view class="share-box">
      <view class="collect" @click="collectArticle">
        <text class="cuIcon-like icon" style='color: #1296db;' v-if="!isCollect" ></text>
        <text class="cuIcon-likefill icon" style='color: #1296db;' v-else ></text>
        <view class="iscollect">{{isCollect ? '已收藏' : '收藏'}}</view>
      </view>
      <view class="sharepyq">
			<button class="btn-pyq" open-type="share" :plain="true">
				<image src="../../../static/image/fenxiang.png"></image>
			</button>
			<view class="isshare">
				分享
			</view>
      </view>
    </view>
    
    <!-- 评论区 -->
    <view class="comment-box">
      <view class="total">
        <view class="total_left">{{comments.length}} 评论</view>
        <view class="total_right">
          <text @click="changeState('hot')" :style="'color:'+[hot?'#1296db;':'#323232']">最热</text>
          <text @click="changeState('new')" :style="'color:'+[hot?'#323232;':'#1296db']" style="border-left:1upx solid #d3d3d3;">最新</text>
        </view>
      </view>
      <!-- 评论列表 -->
      <view class="comment-list">	
        <comment-item :comment="item" :_id="id" :index="index"  @addLike="comments[index].belike++" v-for="(item,index) in comments" :key="index" />
      </view>
      
      <view class="more" v-if="comments.length!=0">
        没有更多内容
      </view>
      
      <view class="shafa" v-if="comments.length==0">还没有人来评论，快来抢沙发吧~</view>
    </view>
    
    <!-- 输入回复 -->
    <view class="answer">
      <text v-if="!userInfo.name">请先登录再发表看法~</text>
      <view v-else>
        <image class="current-avatar" :src="userInfo.avatar"></image>
        <input :focus='sss'  @confirm="pushComment"  v-model="input" placeholder="说说我的看法..." class="textarea" cursor-spacing="20" />
      </view>
    </view>

</view>
		
</template>

<script>
const db = wx.cloud.database();
const _ = wx.cloud.database().command;
import commentItem from '../../../components/comment-item/comment-item.vue'
	export default {
    components:{
      commentItem
    },
		data() {
			return {
					comments:[],
					info:{},
					input:'',
					id:'',
					hot:true,
					isCollect:false,
					userInfo:{
					  name:"",
					  avatar:""
					}
			};
		},	
		onLoad: function(options){
		 this.id=options.id;
          this.userInfo.name = wx.getStorageSync("nickName");
          this.userInfo.avatar= wx.getStorageSync("avt");
          db.collection("user").where({_openid:getApp().globalData.userdata._openid}).get().then(res=>{
            if(res.data[0].article.includes(this.id))
            this.isCollect = true;
          })
		  
		 this.getPageInfo();
		  },
		methods: {
        // 获取文章和评论信息
			getPageInfo(){
			this.getArticle();
			this.getComment();            
        },
        // 获取文章信息
        getArticle(){
			console.log(this.id);
          db.collection("article")
           .where({_id:this.id})
           .get()
           .then(res=>{ 
             this.info=res.data[0]
           })
        },
        // 获取评论信息
        getComment(){
			console.log(this.id);
          db.collection("comment").where({article_id:this.id}).get().then(res => {
            this.comments = res.data[0].comments;
            this.changeState("hot"); //默认以点赞数排序
            for(let i=0;i<this.comments.length;i++){
              this.comments[i].date = this.formatTime(this.comments[i].date)
            }
          })  
        },
        //发表评论
        async pushComment(){
          const user_id = getApp().globalData.userdata._openid;
          let comment = {};
          comment.belike = 0;
          comment.date = new Date();
          comment.user_name = this.userInfo.name;
          comment.user_avatar = this.userInfo.avatar;
          comment.content = this.input;
		  /*
		      发布评论bug源于：在添加评论的时候没有判断comment集合里面有没有对应的数据，
		      也就是说使用update去直接更改定位不到响应的文章id
		      应该先给予判断是否有这个文章的评论id集合，然后
		      如果有的话，使用update直接修改即可，
		      如果没有的话，使用add直接添加进去。
		      */
		      wx.cloud.database().collection('comment').where({
		       article_id: this.id
		      }).get().then(res => {
		       if (res.data.length == 0) {
		        //如果不存在的话，将记录添加进去
		        wx.cloud.database().collection('comment').add({
		         data: {
		          article_id: this.id,
		          comments: []
		         }
		        })
		       }
		       //得将异步变成同步
		       db.collection("comment").where({
		        article_id: this.id
		       }).update({
		        data: {
		         comments: _.push(comment)
		        }
		       }).then(res => {
		        this.input = ""
		        this.getComment();
		        this.addArticleComment();
		        wx.showToast({
		         title: '发表评论成功',
		         icon: 'success',
		         duration: 1000
		        })
		       }).catch(err => {
		        console.log(err)
		       })
		      })
		     },
        //增加文章评论量
        addArticleComment(){
          db.collection("article").where({_id:this.id}).update({
            data:{
              comment:_.inc(1)
            }     
          }).then(res=>{
            console.log(res);
          }).catch(err=>{
            console.log(err)
          })
        },
        //选择评论排序
        changeState(state){
          if(state === "hot"){
            this.hot = true;
             this.comments.sort(function(a,b){
               return b.belike - a.belike;
             })
          }
          else if(state === "new"){
            this.comments.sort(function(a,b){
              return Date.parse(b.date) - Date.parse(a.date);
            })
            this.hot = false;
          }
        },
        //时间格式化工具
        formatTime(date){
			date = new Date(date);
          let month = (date.getMonth() + 1) >= 10 ? date.getMonth() + 1 : ('0' + (date.getMonth() + 1));
          let day = date.getDate() >= 10 ? date.getDate() : ('0' + date.getDate());
          let hour = date.getHours() >= 10 ? date.getHours() : ('0' + date.getHours());
          let min = date.getMinutes() >= 10 ? date.getMinutes() : ('0' + date.getMinutes());
          return month + '-' + day + ' ' + hour + ':' + min;
        },
        
	   collectArticle(){
          if(!this.userInfo.name)
          {
            wx.showToast(
            {
              title: '登录才能收藏文章~',
              icon: 'none',
              duration: 1000
            }) 	
            return;
          }
		if(!this.isCollect)
		{
			console.log(getApp().globalData.userdata._openid);
			db.collection("user").where({_openid:getApp().globalData.userdata._openid}).update({
			  data:{
				article:_.push(this.id)
			  }
			}).then(res=>{
			  console.log(res);
			  getApp().globalData.userdata.article.push(this.id);
			}).catch(err=>{
			  console.log(err);
			})
		wx.showToast(
		{
		  title: '收藏成功',
		  icon: 'success',
		  duration: 1000
		}) 
		}
	  if(this.isCollect){
		  let index = getApp().globalData.userdata.article.indexOf(this.id);
		  getApp().globalData.userdata.article.splice(index,1);
		  db.collection("user").where({_openid:getApp().globalData.userdata._openid}).update({
			data:{
			  article:getApp().globalData.userdata.article
			}    
		  }).then(res=>{
			console.log(res);
			console.log(getApp().globalData.userdata.article)
		  }).catch(err=>{
			console.log(err);
		  })
		wx.showToast(
		{
		  title: '已取消收藏',
		  icon: 'none',
		  duration: 1000
		}) 			  
	}
	  this.isCollect=!this.isCollect
},
			created() {
				wx.setNavigationBarTitle({
					title:'文章'
				})
			},
			onPullDownRefresh() {
				this.getsInfo()
				wx.hideNavigationBarLoading() //完成停止加载
				wx.stopPullDownRefresh() //停止下拉刷新		     
						 	     
			},
			
			onShareAppMessage: function(res) {
			    return {
			      title: '1111',
			      path: '/pages/index/index',
			      imageUrl: 'http://182.92.198.209/ppps.jpg'
			  }
		}
	},
  }
</script>

<style scoped>
  .content{
    		padding-top: 32upx;
    		background-color: #FFFFFF;
        padding-bottom:120upx;
  }
.title{
  		width: 670upx;
  		margin: 0 0 32upx 40upx;
  		color: #323232;
  		font-size: 40upx;
  		font-weight: 550;
}

  
.author{
  display: flex;
  margin:0 32upx;
}
.author-avatar{
  		background-color: #D8D8D8;
  		border-radius: 50%;
  		height: 72upx;
  		width: 72upx;
      margin-right:20upx;
}
.author-name{
  		 color: #323232;
  		 font-size: 34upx;
  		 font-weight: 500;
  		 letter-spacing: -0.82upx;
  		 line-height: 48upx;
}
.author-time{
  color: #9D9B9B;
}
.month{
  margin-right:40upx;

}
	.article p{
		line-height: 52upx;
	}
    
  .article{
    		width: 670upx;
        margin:30upx 40upx;
    		font-size: 30upx;
    		line-height: 52upx;
  }
  .end{
     margin: 32upx 62upx;
		 display: flex;
		 justify-content : space-between;
		 width: 626upx;
		 font-size: 24upx;
		 color: #999999;
  }
   .line{
     margin: auto;
     width: 248upx;
     height: 2upx;
     background-color: #EEEEEE;
   }
   .share-box{
     display: flex;
     color: #999999;
     margin-bottom:80upx;  
   }
     
   .collect{
     width:50%;
     text-align: center;
   }
     
   .icon{
     font-size:54upx;
    
   }
   .iscollect{
     margin-top:8upx;
   }
   .btn-pyq{
     		 width: 150upx;
     		 font-size: 24upx;
     		 color: #999999;
         text-align: center;
         border:none;
   }
   .sharepyq{
     display: flex;
     width: 50%;
     flex-direction: column;
    align-items: center;
    justify-content: center;
   }
   .btn-pyq image{
     width: 54upx;
     height: 44upx;
   }
   .comment-box{
     padding:20upx 32upx;
   }
   .total{
     display: flex;
     justify-content: space-between;
     align-items: center;
   }
   .total_left{
     font-weight: 700;
     font-size:36upx;
     color:#2c2c2c;
   }
   .total_right text{
      padding: 0 15upx;
   }
    .comment-list{
       margin: 30upx 0;
       margin-right:20upx;
    }
   .more{
     		margin-top: 10upx;
     		width: 100%;
     		text-align: center;
     		color:#333333;
     		font-size: 30upx;
     
   }
   .shafa{
     		margin-top: 40upx ;
     		width: 100%;
     		text-align: center;
     		color:#333333;
     		font-size: 30upx;
   }
   .answer{
     display: flex;
     justify-content: center;
     align-items: center;
      padding: 14upx 40upx;
      position: fixed;
      bottom: 0;
      z-index: 10;
      width: 100%;
      height:120upx;
      background-color: #FFFFFF;
      border-top: 2upx solid #D8D8D8;
   }
     
   .answer>view{
     width:100%;
     height:100%;
     display: flex;
     align-items: center;
   }
   .textarea{
        margin-left:30upx;
    		width: 566upx;
     		height: 56upx;
     		background-color: #F5F5F5;
     		 border-radius: 36upx; 
     		caret-color:#CCCCCC;
     		line-height:200upx; 
     		padding: 0 24upx;
     		color: #333333;
   }
   .current-avatar{
      background-color: #D8D8D8;
      border-radius: 50%;
      height: 72upx;
      width: 72upx;
   }

   
</style>
